<script setup>
import {onMounted, ref} from "vue";
import {message} from "ant-design-vue";
import {useRouter} from "vue-router";
import axios from 'axios'
import {HomeOutlined} from '@ant-design/icons-vue'
import {jwtDecode} from "jwt-decode";

const loginStatus = ref(false)
const router = useRouter();
const cityName = ref(sessionStorage.getItem("cityName"));

const handleLogout = async () => {
  try {
    // 发送退出登录请求
    const response = await axios.post(`${window.link}/user/logout`, {}, {
      headers: {
        'access-token': localStorage.getItem('access-token')
      }
    })
    if (response.data.code === 200) {
      // 清除本地存储的 token
      localStorage.clear()
      sessionStorage.clear()
      // 显示成功消息
      message.success('退出登录成功')
      // 跳转到登录页面
      await router.push('/user/login/loginByPhone')
    } else {
      message.error(response.data.message || '退出失败，请重试')
    }
  } catch (error) {
    console.error('退出登录失败:', error)
    message.error('退出失败，请重试')
  }
}

if(cityName.value === null || cityName.value === ""){
  cityName.value = "呼和浩特"
}

const selectAllArea = () => {
  router.push("/selectArea");
}
const username = sessionStorage.getItem("username");
router.push("/home/home1")

// 添加激活状态控制
const activeNav = ref('home') // 默认首页激活

const goMyself = () => {
  router.push("/home/myself")
  activeNav.value = 'myself'
}
const goHome = () => {
  router.push("/home/home1")
  activeNav.value = 'home'
}
const token = localStorage.getItem("access-token");
if (token != null) {
  loginStatus.value = true;
}

const userRole = ref(false);
const fun = () => {
  try {
    const decodedToken = jwtDecode(token);
    // console.log(decodedToken)
    const userRoleTemp = decodedToken.role; // 确保后端 token 中包含 role 字段
    if(userRoleTemp === 'LANDLORD'){
      userRole.value = true;
      sessionStorage.setItem("userRole",true);
      sessionStorage.setItem("userId",decodedToken.userId)
    }

  } catch (error) {
    console.error('Token 解析失败:', error);
    message.error('登录信息解析失败');
  }
}

const goHelp = () => {
  router.push("/home/help")
}
fun()
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <div class="bg-white shadow-sm">
      <div class="container mx-auto px-8">
        <div class="flex items-center justify-between h-14">
          <div class="flex items-center ">
            <span @click="selectAllArea"
                  class="text-gray-600 hover:text-orange-500 text-sm cursor-pointer">[切换城市]
            </span>
            <span class="text-gray-600 hover:text-orange-500 text-sm cursor-pointer">
              [{{cityName}}]
            </span>
          </div>
          <div class="flex items-center space-x-6">
            <div v-if="!loginStatus">
              <router-link to="/user/login" class="text-gray-600 hover:text-orange-500 text-sm">登录
              </router-link>
              <span>/</span>
              <router-link to="/user/register" class="text-gray-600 hover:text-orange-500 text-sm">
                注册
              </router-link>
            </div>
            <div v-if="loginStatus">
              <span class="space-x-2">
                <span>{{ username }}</span>
                <span class="text-gray-600 hover:text-orange-500 text-sm cursor-pointer mx-2"
                      @click="handleLogout">退出</span>
                <router-link v-if="userRole" to="/landlord" class="text-gray-600 hover:text-orange-500 text-sm mx-2">
                  发布房源
                </router-link>
              </span>
              <span class="ml-4">
                <span class="text-gray-600 hover:text-orange-500 text-sm whitespace-nowrap cursor-pointer"
                      @click="goMyself">个人中心</span>
              </span>
            </div>
            <a @click="goHelp" class="text-orange-500 text-sm cursor-pointer">在线客服</a>
            <home-outlined class="hover:text-orange-500 cursor-pointer" @click="goHome"></home-outlined>
          </div>

        </div>
      </div>
    </div>

    <!-- 更细的分隔线 -->
    <div class="divider"></div>

    <!-- 主要内容区域 -->
    <router-view></router-view>
  </div>
</template>

<style scoped>
.divider {
  height: 1px;
  background-color: #edf2f7;
  border: none;
}

</style>